const jwt = require('jsonwebtoken');
const config = require('../config/config.default');

class JWT {
  // 生成token
  static generate(user) {
    const userInfo = {
      userId: user._id,
      username: user.username,
      email: user.email,
      role: user.role,
      studentId: user.studentId
    };

    return jwt.sign(userInfo, config.JWT_SECRET, {
      expiresIn: '7d'
    });
  }

  // 验证token
  static verify(token) {
    try {
      return jwt.verify(token, config.JWT_SECRET);
    } catch (error) {
      return null;
    }
  }

  // 从请求头中获取并验证token
  static getTokenInfo(authorization) {
    if (!authorization) {
      return null;
    }

    try {
      const token = authorization.replace('Bearer ', '');
      return this.verify(token);
    } catch (error) {
      return null;
    }
  }
}

module.exports = JWT; 